//index.js
//获取应用实例
const app = getApp()
let Axios = require('../../../common/js/ajax.js');
let Mtils = require('../../../common/js/Mtils.min.js');
let util = require('../../../common/utils/util.js'); //转换时间插件
let webim = require('../../../common/utils/webim_wx.js'); //腾讯云im包
let webimhandler = require('../../../common/utils/webim_handler.js'); //这个是所有事件的腾讯js，这个页面需要用到登录
Mtils = Mtils.Mtils
var page = 1;
var switch_p = true
var selSess = null;
var selType = webim.SESSION_TYPE.C2C;
var selToID, selSessHeadUrl;
var loginInfo = {
	'sdkAppID': app.data.Config.sdkappid, //用户所属应用id,必填
	'appIDAt3rd': app.data.Config.sdkappid, //用户所属应用id，必填
	'accountType': app.data.Config.accountType, //用户所属应用帐号类型，必填
	'identifier': app.globalData.identifier, //当前用户ID,必须是否字符串类型，选填
	'identifierNick': app.globalData.identifierNick, //当前用户昵称，选填
	'userSig': app.globalData.userSig, //当前用户身份凭证，必须是字符串类型，选填
};
Page({
	data: {
		openid: '',
		nickName: '',
		avatarUrl: '',
		curentNav: 2, //当前导航
		menu: 0,
		cur_menu: 0,
		list: [],
		noData: '/img/noData.png', //无数据的图片
		contactList: [],
		delBtnWidth: 80,
		startX: "",
		numChat:0,
		newest:{},
		isIpx: app.globalData.isIpx ? true : false
	},
	//事件处理函数
	onUnload() {
		//this.quitClick()
		console.log('onUnload')
	},
	onLoad: function() {		
		var _this = this;
		this.load = this.selectComponent("#loading");
		_this.load.loadIng()
		this.uid = app.globalData.uid || ''
		this.Md5 = Mtils.security.hex_md5(this.uid) + app.globalData.secret;
		this.Md5 = Mtils.security.hex_md5(this.Md5);
		this.timesp = Mtils.now();
		if (app.globalData.nickName && app.globalData.avatarUrl) {
			this.setData({
				nickName: app.globalData.nickName,
				avatarUrl: app.globalData.avatarUrl
			})
		}
	},
	onShow() {
		var _this = this;
		selToID = ''
		wx.showLoading({
			mask:true
		})
		Axios.get(app.globalData.baseUrl + 'App/Message/Message/get_no_read_count', {
			uid: this.uid,
			time: this.timesp,
			sign: this.Md5,
		}, (res) => {
			console.log(res)
			if (res.status == 1) {
				var data = res.info
					_this.setData({
						newest:data
					})						
			} else {
				_this.showModal(res)
			}
		})
		loginInfo = {
			'sdkAppID': 1400178898, //用户所属应用id,必填
			'appIDAt3rd': 1400178898, //用户所属应用id，必填
			'accountType': app.data.Config.accountType, //用户所属应用帐号类型，必填
			'identifier': app.globalData.identifier, //当前用户ID,必须是否字符串类型，选填
			'identifierNick': app.globalData.identifierNick, //当前用户昵称，选填
			'userSig': app.globalData.userSig, //当前用户身份凭证，必须是字符串类型，选填
		};
		webimhandler.init({ //初始化的方法
			accountMode: app.data.Config.accountMode,
			accountType: app.data.Config.accountType,
			sdkAppID: 1400178898,
			selType: webim.SESSION_TYPE.C2C, //私聊
			id: selToID, //如果是经纪人，则填agent_member_id ,如果是普通用户则填经纪人id
			name: app.globalData.nickName,
			icon: app.globalData.avatarUrl,
			that: _this
		});
		if (webim.checkLogin()) { //检查是否登录返回true和false,不登录则重新登录
			console.log('已登录')
			_this.quitClick(function(){
				_this.sdkLogin(_this, app, selToID, function() {
					_this.initRecentContactList()
				});				
			})			
		} else {
			console.log('登录成功')
			_this.sdkLogin(_this, app, selToID, function() {
				_this.initRecentContactList()
			});
		}
	},
	onHide() {
		console.log('onHide')
		//this.quitClick()
	},
	onReady: function() {
		wx.setNavigationBarTitle({
			title: '我的消息'
		})
	},
	handleEvtap: function(e) {
		var _this = this;
		page = 1;
		var index = e.currentTarget.dataset.index;
		this.setData({
			menu: index
		})
		if (this.data.menu == 1) {
			_this.load.showIng()
			Axios.get(app.globalData.baseUrl + 'App/Message/Message/get_notice', {
				uid: this.uid,
				time: this.timesp,
				sign: this.Md5,
			}, (res) => {
				console.log(res)
				if (res.status == 1) {
					var data = res.info
					_this.setData({
						list: data
					})
					_this.load.loadIng()
				} else {
					_this.showModal(res)
				}
			})
		}
	},
	showModal: function(error) {
		wx.showModal({
			content: error.msg,
			showCancel: false,
		})
	},
	onReachBottom: function() {
		var _this = this;
		if (switch_p && this.data.menu == 1) {
			wx.showLoading({
				title: '玩命加载中',
				mask:true
			})
			switch_p = false
			page = page + 1;
			Axios.get(app.globalData.baseUrl + 'App/Message/Message/get_notice?p=' + page, {
				uid: this.uid,
				time: this.timesp,
				sign: this.Md5,
			}, (res) => {
				console.log(res)
				if (res.status == 1) {
					var data = res.info
					var temp = _this.data.list.concat(data)
					_this.setData({
						list: temp
					})
					switch_p = true
					wx.hideLoading();
				} else {
					_this.showModal(res)
				}
			})
		}
	},
	initRecentContactList: function() {
		var that = this;
		webim.getRecentContactList({ //获取会话列表的方法
			'Count': 10 //最近的会话数 ,最大为 100
		}, function(resp) {
			if (resp.SessionItem) {
				if (resp.SessionItem.length == 0) {
					that.setData({
						isNoData: false,
					})
					wx.hideLoading()
				} else if (resp.SessionItem.length > 0) {
					that.setData({
						contactList: resp.SessionItem,
						isNoData: true
					})
					var userId = that.data.contactList.map((item, index) => {
						return item.To_Account
					})
					that.getAvatar(userId, that.data.contactList, function(data) {
						data = data.map((item, index) => {
							if (item.MsgShow == '[其他]') {
								item.MsgShow = '[房源信息]'
							}
							return item;
						})
						// 初始化最近会话的消息未读数(监听新消息事件)
						webim.syncMsgs();
						var sessMap = webim.MsgStore.sessMap();
						var id = "C2C" + userId
						var num = 0
						setTimeout(function() {
							data = data.map((item, index) => {
								if (sessMap.hasOwnProperty("C2C" + item.LastC2cMsgFrom_Account)) {
									item.UnreadMsgCount = sessMap["C2C" + item.LastC2cMsgFrom_Account].unread()
									num += item.UnreadMsgCount
								}
								item.txtStyle = '';
								return item;
							})
							//console.log(data)
							that.setData({
								contactList: data,
								numChat: num
							})
							wx.hideLoading();
						}, 1000)
					})
				} else {
					wx.hideLoading()
					return;
				}
			} else {
				wx.hideLoading()
			}
		}, function(resp) {
			//错误回调
		});
	},
	getAvatar: function(userId, item, callback) {
		if (!callback) {
			callback = () => {}
		}
		var that = this;
		var tag_list = ['Tag_Profile_IM_Nick', 'Tag_Profile_IM_Image']
		//用户id
		var account = userId
		var options = {
			From_Account: userId,
			To_Account: account,
			LastStandardSequence: 0,
			TagList: tag_list,
		};
		var contactList = [];
		webim.getProfilePortrait(
			options,
			function(res) {
				var UserProfileItem = res.UserProfileItem;
				var C2cNick, C2cImage;
				//console.log(res.UserProfileItem)
				for (var i = 0; i < UserProfileItem.length; i++) {
					var data = UserProfileItem[i].ProfileItem;
					// 循环添加昵称和头像
					contactList = item.map((item, index) => {
						item.C2cNick = UserProfileItem[index].ProfileItem[0].Value					
						item.C2cImage = UserProfileItem[index].ProfileItem[1].Value
						return item;
					})
				}
				contactList = contactList.map((item, index) => {
					var born = new Date(item.MsgTimeStamp * 1000)
					var MsgTimeStamp = util.formatTime(born)
					item.MsgTimeStamp = MsgTimeStamp;
					return item;
				})
				callback(contactList)
			},
			function(err) {
				console.log(err);
			}
		)
	},
	sdkLogin: function(that, app, selToID, callback) {
		var that = this
		if (!callback) {
			callback = () => {}
		}
		//1v1单聊的话，一般只需要 'onConnNotify' 和 'onMsgNotify'就行了。
		//监听连接状态回调变化事件
		var onConnNotify = function(resp) {
			switch (resp.ErrorCode) {
				case webim.CONNECTION_STATUS.ON:
					webim.Log.warn('连接状态正常...');
					break;
				case webim.CONNECTION_STATUS.OFF:
					webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
					break;
				default:
					webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
					break;
			}
		};
		var onMsgNotify = function(msg) {
			//console.log(msg)
			if (msg.length > 1) {
				return false
			}
			var MsgTimeStamp = msg[0].time
			webimhandler.onBigGroupMsgNotify(msg, function(msgs) {
				var temp = that.data.contactList
				var flag = true
				var keyvalue = 0
				var num = that.data.numChat
				try {
					temp.forEach(function(item, key) {
						if (item.LastC2cMsgFrom_Account == msgs.fromAccountNick) {
							flag = false
							keyvalue = key
							throw new Error("EndIterative");
						}
					})
				} catch (e) {
					if (e.message != "EndIterative") throw e;
				};
				if (!flag) {
					temp[keyvalue].MsgShow = msgs.content
					var unreadinfo = {}
					temp[keyvalue].UnreadMsgCount += 1
					num += 1
					unreadinfo[msgs.fromAccountNick] = temp[keyvalue].UnreadMsgCount
					that.setData({
						contactList: temp,
						numChat: num
					})
				} else {
					var obj = {
						C2cImage: '',
						C2cNick: '',
						MsgTimeStamp: MsgTimeStamp,
						MsgShow: msgs.content,
						UnreadMsgCount: 1,
						LastC2cMsgFrom_Account: msgs.fromAccountNick,
						txtStyle: ''
					}
					num += 1
					var arr = []
					arr.push(obj)
					var id = [];
					id.push(msgs.fromAccountNick)
					that.getAvatar(id, arr, function(data) {
						data = data.map((item, index) => {
							if (item.MsgShow == '[其他]') {
								item.MsgShow = '[房源信息]'
							}
							return item;
						})
						temp.unshift(data[0])
						that.setData({
							contactList: temp,
							numChat: num
						})
						wx.hideLoading();
					})
				}
			})
		}
		//监听事件
		var listeners = {
			"onConnNotify": onConnNotify, //监听连接状态回调变化事件,必填			
			"onMsgNotify": onMsgNotify
		};
		//其他对象，选填
		var options = {
			'isAccessFormalEnv': true, //是否访问正式环境，默认访问正式，选填
			'isLogOn': false //是否开启控制台打印日志,默认开启，选填
		};
		//sdk登录(独立模式)
		webim.login(loginInfo, listeners, options, function(resp) {
			callback()
		}, function(err) {
			console.log("登录失败", err.ErrorInfo)
		});
	},
	linkChat: function(e) {
		var id = e.currentTarget.dataset.id
		wx.navigateTo({
			url: '/pages/center/chatRoom/chatRoom?id=' + e.currentTarget.dataset.id + '&name=' + e.currentTarget.dataset.name +
				'&icon=' + e.currentTarget.dataset.icon,
		})
// 		this.quitClick(function(){
// 			wx.navigateTo({
// 				url: '/pages/center/chatRoom/chatRoom?id=' + e.currentTarget.dataset.id + '&name=' + e.currentTarget.dataset.name +
// 					'&icon=' + e.currentTarget.dataset.icon,
// 			})
// 		})
		
		//this.delChat(1, id, index)
	},
	linkOrder:function(){
		wx.navigateTo({
			url: '/pages/center/notice/notice'
		})
	},
	delChat: function(e) {
		var to_id = e.currentTarget.dataset.id
		var index = e.currentTarget.dataset.index
		var sess_type = 1;
		var that = this
		var data = {
			'To_Account': to_id,
			'chatType': sess_type
		}
		webim.deleteChat(
			data,
			function(resp) {
				var temp = that.data.contactList
				temp.splice(index, 1)
				that.setData({
					contactList: temp
				})
			}
		);
	},
	quitClick: function(callback) {
		if (loginInfo.identifier) {
			//sdk登出
			webim.logout(callback);
		} else {
			// alert('未登录');
		}
	},
	touchS: function(e) {
		if (e.touches.length == 1) {
			this.setData({
				//设置触摸起始点水平方向位置
				startX: e.touches[0].clientX
			});
		}
	},
	touchM: function(e) {
		if (e.touches.length == 1) {
			//手指移动时水平方向位置
			var moveX = e.touches[0].clientX;
			//手指起始点位置与移动期间的差值
			var disX = this.data.startX - moveX;
			var delBtnWidth = this.data.delBtnWidth;
			var txtStyle = "";
			if (disX == 0 || disX < 0) { //如果移动距离小于等于0，说明向右滑动，文本层位置不变
				txtStyle = "left:0px";
			} else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离
				txtStyle = "left:-" + disX + "px";
				if (disX >= delBtnWidth) {
					//控制手指移动距离最大值为删除按钮的宽度
					txtStyle = "left:-" + delBtnWidth + "px";
				}
			}
			//获取手指触摸的是哪一项
			var index = e.currentTarget.dataset.index;
			var list = this.data.contactList;
			console.log(list, index)
			list[index].txtStyle = txtStyle;
			//更新列表的状态
			this.setData({
				contactList: list
			});
		}
	},
	touchE: function(e) {
		if (e.changedTouches.length == 1) {
			//手指移动结束后水平位置
			var endX = e.changedTouches[0].clientX;
			//触摸开始与结束，手指移动的距离
			var disX = this.data.startX - endX;
			var delBtnWidth = this.data.delBtnWidth;
			//如果距离小于删除按钮的1/2，不显示删除按钮
			var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
			//获取手指触摸的是哪一项
			var index = e.currentTarget.dataset.index;
			var list = this.data.contactList;
			list[index].txtStyle = txtStyle;
			//更新列表的状态
			this.setData({
				contactList: list
			});
		}
	},
	//获取元素自适应后的实际宽度
	getEleWidth: function(w) {
		var real = 0;
		try {
			var res = wx.getSystemInfoSync().windowWidth;
			var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应
			real = Math.floor(res / scale);
			return real;
		} catch (e) {
			return false;
			// Do something when catch error
		}
	},
	initEleWidth: function() {
		var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
		this.setData({
			delBtnWidth: delBtnWidth
		});
	},
	showModal: function(error) {
		wx.showModal({
			content: error.msg,
			showCancel: false,
		})
	},
})
